package com.bourne.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bourne.enums.BizCodeEnum;
import com.bourne.exception.BizException;
import com.bourne.model.BaseCoreDO;
import com.bourne.model.PageDomain;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 分页工具
 */
@Configuration
@Component
public class PageUtils<T extends BaseCoreDO> {

    private static final String PAGE_NUM = "pageNum";

    private static final String PAGE_SIZE = "pageSize";


    public Page<T> pageInfoInit() {
        PageDomain pageDomain = pageDomainInit();
        return new Page<T>(pageDomain.getPageNum(), pageDomain.getPageSize());
    }

    private Integer getPageParameterInit(String name) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes)requestAttributes;
        try {
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            return Integer.parseInt(request.getParameter(name));
        } catch (Exception e) {
            throw new BizException(BizCodeEnum.REQUEST_ARGS_NOT_VALID);
        }
    }

    public Map<String, Object> pageDataMap(IPage<T> pageData) {
        Map<String, Object> pageMap = new HashMap<>(3);
        pageMap.put("total_record", pageData.getTotal());
        pageMap.put("total_page", pageData.getPages());
        pageMap.put("current_data", pageData.getRecords());
        return pageMap;
    }

    private PageDomain pageDomainInit() {
        Integer pageNum = getPageParameterInit(PAGE_NUM);
        Integer pageSize = getPageParameterInit(PAGE_SIZE);
        return new PageDomain(pageNum, pageSize);
    }
}
